#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
 #include <semaphore.h>

int num = 0;
sem_t sem;//定义一个信号量对象
//线程函数
//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
void *threadFun(void *arg)
{
    //上锁
    sem_wait(&sem);
    int i = 1000000;
    
    while(i--)
    {
        num++;
    }
    sem_post(&sem);
}
 
int main()
{
    //初始化信号量
    sem_init(&sem,0,1);

    pthread_t tid1;
    pthread_t tid2;
    //创建线程
    pthread_create(&tid1,NULL,threadFun,NULL);
    pthread_create(&tid2,NULL,threadFun,NULL);
    //创建信号量，实现PV操作
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

    printf("num = %d\n",num);
    sem_destroy(&sem);

    return 0;
}